<template>
  <view>
    <!-- #ifndef  H5 -->
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
          :is-back="true"
          :title-bold="true"
          :is-fixed="false"
          title="详情"
          title-color="#000000"
          :border-bottom="false"
          back-icon-name="arrow-leftward"
          back-icon-color="#000000"
          :background="{ background: 'rgba(256,256, 256,0)' }"
      ></u-navbar>
    </u-sticky>
    <!-- #endif -->
    <view class="order-details">
      <view class="order-status-desc">{{ orderDetail.order_status_desc }}...</view>
      <view class="main">
        <view class="order-info contain">
          <view class="item row-between">
            <view class="title">订单编号:</view>
            <view class="black">{{ orderDetail.order_sn }}</view>
          </view>
          <view class="item row-between">
            <view class="title">服务名称:</view>
            <view class="black">{{ orderDetail.order_type_desc }}</view>
          </view>
          <view class="item row-between">
            <view class="title">企业名称:</view>
            <view class="black">{{ orderDetail.company_name }}</view>
          </view>
          <view class="item row-between">
            <view class="title">联系人:</view>
            <view class="black">{{ orderDetail.company_contact }}</view>
          </view>
          <view class="item row-between">
            <view class="title">订单金额:</view>
            <view class="black price">¥{{ orderDetail.total_amount }}</view>
          </view>
          <view class="item row-between">
            <view class="title">下单时间</view>
            <view class="black">{{ orderDetail.create_time }}</view>
          </view>
          <view v-if="orderDetail.pay_time" class="item row-between">
            <view class="title">付款时间</view>
            <view class="black">{{ orderDetail.pay_time }}</view>
          </view>
        </view>
        <view
            class="footer bg-white row fixed"
            v-if="
            orderDetail.cancel_btn ||
            orderDetail.delivery_btn ||
            orderDetail.take_btn ||
            orderDetail.del_btn ||
            orderDetail.pay_btn||
            orderDetail.negotiate_cancel_btn
          "
        >
          <view v-if="orderDetail.negotiate_cancel_btn" class="footer-btn">
            <button
                size="sm"
                class="plain br60"
                hover-class="none"
                @tap="cancelOrder"
            >
              协商取消
            </button>
          </view>
          <view v-if="orderDetail.cancel_btn" class="footer-btn">
            <button
                size="sm"
                class="plain br60"
                hover-class="none"
                @tap="cancelOrder"
            >
              取消订单
            </button>
          </view>
          <view v-if="orderDetail.take_btn" class="footer-btn">
            <button
                size="sm"
                class="plain br60 primary red"
                hover-class="none"
                @tap.stop="comfirmOrder"
            >
              确认完成
            </button>
          </view>
          <view v-if="orderDetail.del_btn" class="footer-btn">
            <button
                size="sm"
                class="plain br60"
                hover-class="none"
                @tap="delOrder"
            >
              删除订单
            </button>
          </view>
          <view class="ml20 footer-btn" v-if="orderDetail.pay_btn" >
            <button size="sm" class="bg-primary br60 white" @tap="payNow">
              立即付款
            </button>
          </view>
        </view>
      </view>
    </view>

    <loading-view v-if="isFirstLoading"></loading-view>
    <order-dialog
        ref="orderDialog"
        :orderId="orderDetail.id"
        :type="type"
        @refresh="onRefresh"
    ></order-dialog>
    <loading-view
        v-if="showLoading"
        background-color="transparent"
        :size="50"
    ></loading-view>
  </view>
</template>

<script>
import {
  getOrderDetail,
  getwechatSyncCheck,
  getwxReceiveDetail,
  confirmOrder,
} from "@/api/order";
import {compareWeChatVersion} from "@/utils/tools";

import {prepay} from "@/api/app";
import {wxpay, alipay} from "@/utils/pay";

export default {
  data() {
    return {
      orderDetail: {},
      team: {},
      isFirstLoading: true,
      type: 0,
      cancelTime: 0,
      showCancel: "",
      showLoading: false,
      imageQR: "",
      priceShow: false,
    };
  },

  components: {},
  props: {},

  onLoad: function (options) {
    this.id = options.id;
    this.getOrderDetailFun();
  },

  onUnload() {
    uni.$off("payment");
  },

  onShow() {
    this.getOrderDetailFun();
  },

  methods: {
    onRefresh() {
      uni.$emit("refreshorder");
      const {type} = this;
      if ([0, 2].includes(type)) {
        this.getOrderDetailFun();
      } else if (type == 1) {
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      }
    },
    orderDialog() {
      this.$refs.orderDialog.open();
    },

    delOrder() {
      this.type = 1;
      this.$nextTick(async () => {
        this.orderDialog();
      });
    },
    // 小程序确认收货
    comfirmReceive(transaction_id) {
      return new Promise((resolve, reject) => {
        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            transaction_id,
          },
          success({extraData}) {
            if (extraData.status == "success") {
              resolve("确认完成");
            } else {
              resolve("取消完成");
            }
          },
          fail(err) {
            reject(err);
          },
        });
      });
    },
    //查询是否收货成功
    querycomfirmReceive(id) {
      return new Promise((resolve, reject) => {
        getwechatSyncCheck({id})
            .then(({data}) => {
              if (data.order.order_state === 4) {
                resolve("已确认完成");
              } else {
                reject("未确认完成");
              }
            })
            .catch((err) => {
              reject(err);
            });
      });
    },

    comfirmOrder() {
      this.type = 2;
      this.$nextTick(async () => {
        // #ifdef MP-WEIXIN
        let res = {};
        if (this.orderDetail.pay_way === 1) {
          res = await getwechatSyncCheck({id: this.id});
          console.log(res);
        }
        if (
            compareWeChatVersion("2.6.0") === 1 &&
            wx.openBusinessView &&
            this.orderDetail.pay_way === 1 &&
            res.data.order.order_state !== 1
        ) {
          try {
            const {data} = await getwxReceiveDetail({
              order_id: this.id,
            });
            await this.comfirmReceive(data.transaction_id);
            await this.querycomfirmReceive(this.id);
            await confirmOrder(this.id);
          } catch (error) {
            console.log(error);
          }
          this.getOrderDetailFun();
        } else {
          this.orderDialog();
        }
        // #endif

        // #ifndef MP-WEIXIN
        this.orderDialog();
        // #endif
      });
    },

    cancelOrder() {
      this.type = 0;
      this.$nextTick(() => {
        this.orderDialog();
      });
    },

    payNow() {
      uni.$on("payment", (params) => {
        setTimeout(() => {
          if (params.result) {
            this.$toast({
              title: "支付成功",
            });
            this.getOrderDetailFun();
            uni.$emit("refreshorder");
          } else {
            this.$toast({
              title: "支付失败",
            });
          }
        }, 500);
      });

      uni.navigateTo({
        url: `/pages/payment/payment?from=${"order"}&order_id=${this.id}`,
      });
    },

    getOrderDetailFun() {
      getOrderDetail(this.id)
          .then((res) => {
            if (res.code == 1) {
              this.cancelTime = res.data.order_cancel_time - Date.now() / 1000;
              this.orderDetail = res.data;
              this.team = res.data.team || {};
              this.$nextTick(() => {
                this.isFirstLoading = false;
              });
            } else {
              setTimeout(() => uni.navigateBack(), 1500);
            }
            return res.data;
          })
          .then((data) => {
            if (data.delivery_type === 2) {
              // 提货码
              this.$nextTick(function () {
                const refQR = this.$refs["qrcode"];
                refQR._makeCode();
              });
            }
          });
    },
  },
  computed: {
    showQRSelffetch() {
      let result = false;

      if (this.orderDetail.order_status) {
        result = true;
      }

      if (this.orderDetail.order_type == 2) {
        this.orderDetail.team_status == 1 ? (result = true) : (result = false);
      }

      return result;
    },
    teamStatus() {
      return (status) => {
        switch (status) {
          case 0:
            return "拼团中";
          case 1:
            return "拼团成功";
          case 2:
            return "拼团失败";
        }
      };
    },
    getOrderType() {
      return (type) => {
        switch (type) {
          case 0:
            return "普通订单";
          case 1:
            return "秒杀订单";
          case 2:
            return "拼团订单";
          case 3:
            return "砍价订单";
        }
      };
    },
  },
};
</script>
<style lang="scss">
page {
  background-image: url("../../static/images/my_bg.jpg");
  background-size: 100%;
  background-repeat: no-repeat;
}

.order-details {
  position: relative;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.order-details .header-bg {
  position: absolute;
  top: 0;
  width: 100%;
  height: 200rpx;
  background-color: $-color-primary;
  z-index: 0;
}

.order-details .goods .status {
  height: 88rpx;
  padding: 0 20rpx;
}

.order-details .main {
  position: relative;
  z-index: 1;
}

.order-details .contain {
  margin: 0 20rpx 20rpx;
  border-radius: 14rpx;
  background-color: #fff;
}

.order-details .header {
  padding: 24rpx 40rpx;
  box-sizing: border-box;
}

.order-details .img-line {
  height: 1.5px;
  width: 100%;
  display: block;
}

.order-details .address-wrap {
  height: 164rpx;
  padding: 0 24rpx;
}

.order-details .order-info {
  padding: 12rpx 0;
}

.order-details .order-info .item {
  padding: 12rpx 24rpx;
}

.order-details .order-info .item .title {
  width: 180rpx;
  flex: none;
  font-size: 24rpx;
  color: #959faf
}

.order-details .order-info .item .black {
  color: #030303;
  font-size: 24rpx;
}

.order-details .order-info .item .price {
  color: #2d6af4;
}

.order-details .price > view {
  height: 60rpx;
  padding: 0 24rpx;
}

.order-details .footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  padding: 0 24rpx;
  box-sizing: content-box;
  padding-bottom: env(safe-area-inset-bottom);
}

.footer-btn {
  margin: auto;
}

.footer .plain {
  border: 1px solid #ecebf3;
}

.footer .plain.red {
  border: 1px solid $-color-primary;
}

.tips-dialog {
  height: 230rpx;
  width: 100%;
}

.order-details .invite-btn {
  background: linear-gradient(270deg, #ff2c3c 0%, #f95f2f 100%);
  margin: 30rpx 26rpx 40rpx;
}

.receiving-card {
  display: flex;
  align-items: center;
  min-height: 160rpx;
  padding: 20rpx;
  border-top: 1px solid #f2f2f2;
}

.receiving-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.receive {
  position: relative;
}

.delivery--die {
  position: absolute;
  top: 0;
  right: 30rpx;
}

.receive-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 460rpx;
}

.qr-contain {
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 140px;
  height: 140px;
  padding: 8px;
  border: 1px solid #cccccc;
  border-radius: 5px;
}

.qr-contain--die {
  position: relative;
}

.qr-contain--die::before {
  position: absolute;
  z-index: 99;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: block;
  content: "";
  background-color: rgba(255, 255, 255, 0.5);
}

.qr-code {
  padding: 8rpx 30rpx;
  border-radius: 60px;
  background-color: #f6f6f6;
}

.receive-info {
  padding-left: 20rpx;
}

.receive-info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  padding-right: 30rpx;
}

.receive-info-item:nth-child(n + 2) {
  border-top: $-dashed-border;
}

.order-status-desc {
  padding: 20rpx 30rpx;
  font-size: 44rpx;
  color: #000206;
  font-weight: bold;
}
</style>
